import type { Record, Range } from '@/types/index'

// obj去除空属性
export const removeProperty = (obj: Record) => {
  Object.keys(obj).forEach((item) => {
    if (['', undefined, null].indexOf(obj[item]) === -1) {
      delete obj[item]
    }
  })
  return obj
}

// 去重 unique
export const uniqueArr = (arr: []) => {
  return [...new Set(arr)]
}

// json通用转换
export const jsonPares = (string?: string): unknown => {
  if (!string) return null
  try {
    return JSON.parse(string)
  } catch (err) {
    return null
  }
}
export const jsonStringify = (json?: object): string => {
  if (!json) return ''
  try {
    return JSON.stringify(json)
  } catch (err) {
    return ''
  }
}

// 对象数组数据结构互换（仅2层结构）
export const objToArr = (obj: Record, k = 'key', v = 'value') => {
  const list = []
  const keys = Object.keys(obj)
  for (let i = 0; keys.length < i; i++) {
    const key = keys[i]
    const value = obj[key]
    list.push({ [k]: key, [v]: value })
  }
  return list
}
export const arrToObj = (arr: Record[], k = 'key', v = 'value') => {
  const obj: Record = {}
  arr.forEach((item) => {
    const key = item[k]
    obj[key] = item[v]
  })
  return obj
}

// 在多层list中寻找item
export const findItem = (list: Record[], value?: number | string, prop = 'id') => {
  if (!value && value !== 0) return null
  const fn = (list: Record[]) => {
    let result: unknown = null
    for (let i = 0; i < list.length; i++) {
      const item = list[i]
      if (item[prop] === value) {
        return item
      } else if (item.children) {
        result = fn(item.children)
        if (result) return result
      }
    }
    return result
  }
  return fn(list)
}

// 数组排序。如果是数组对象，根据数组对象的某个key排序
// 排序规则：内置规则（0-9a-z）；规则外的排在最后
export const sortArr = (arr = [], key?: string) => {
  return arr.sort((a: never, b: never) => {
    const order = [
      '0',
      '1',
      '2',
      '3',
      '4',
      '5',
      '6',
      '7',
      '8',
      '9',
      'a',
      'b',
      'c',
      'd',
      'e',
      'f',
      'g',
      'h',
      'i',
      'g',
      'k',
      'l',
      'm',
      'n',
      'o',
      'p',
      'q',
      'r',
      's',
      't',
      'u',
      'v',
      'w',
      'x',
      'y',
      'z'
    ]
    if (typeof key === 'string') {
      let m = order.indexOf(a[key][0])
      let n = order.indexOf(b[key][0])
      if (m === -1) m += 99
      if (n === -1) n += 99
      const num = m - n
      return num
    } else {
      const num: number = order.indexOf(a) - order.indexOf(b)
      return num
    }
  })
}

// 在range中获取某项
export const getRangeItem = (range: Range[], value: string | number) => {
  return range.filter((item) => item.value == value)[0] || null
}

export default {
  removeProperty,
  uniqueArr,

  jsonPares,
  jsonStringify,
  objToArr,
  arrToObj,

  findItem,
  sortArr,
  getRangeItem
}
